const Answers = require('../models/Answers')
const Questions = require('../models/Questions')

class AnswersCtl {
    async findAll(ctx) {
        const perPage = Math.max(ctx.query.perPage * 1, 1)
        const page = Math.max(ctx.query.page * 1, 1)
        const skip = (page - 1) * perPage
        const list = await Answers.find().limit(perPage).skip(skip)
        const total = await Answers.find().countDocuments()
        ctx.body = {
            list,
            perPage,
            page,
            total
        }
    }
    async find(ctx) {
        // Math.max在接受的参数中选择最大的一个
        // 每页条数
        const perPage = Math.max(ctx.query.perPage * 1, 10) || 10
        // 当前页
        const page = Math.max(ctx.query.page * 1, 1) || 1
        // 跳过的条数
        const skip = (page - 1) * perPage
        // 分页 模糊搜索
        const q = new RegExp(ctx.query.q)
        const list = await Answers.find({ content: q, questionId: ctx.params.questionId }).limit(perPage).skip(skip).sort({createdAt: -1})
        const total = await Answers.find({ content: q, questionId: ctx.params.questionId }).countDocuments()
        const totalPage = Math.ceil(total / perPage)
        ctx.body = {
            list,
            total,
            perPage,
            page,
            totalPage
        }
    }
    async checkAnswerExist(ctx, next) {
        const answer = await Answers.findById(ctx.params.id).select('+answerer')
        if (!answer) {
            ctx.throw(404, '答案不存在')
        }
        // ctx.params.questionId存在才检查，是不是一致
        // 只有删改查答案，才检查此逻辑，赞和踩答案不检测
        if (ctx.params.questionId && answer.questionId !== ctx.params.questionId) {
            ctx.throw(404, '该问题下没有此答案')
        }
        // 答案存在，则存储作答者信息
        console.log(answer);
        ctx.state.answer = answer
        await next()
    }
    async findById(ctx) {
        const { fields = '' } = ctx.query
        const selectFields = fields.split(',').filter(f => f).map(f => f => '+ ' + f).join('')
        const answer = await Answers.findById(ctx.params.id).select(selectFields).populate('answerer')
        ctx.body = answer
    }
    async findQAll(ctx) {
        // const answer=await Answers.find({answerer:ctx.params.id}).populate('answerer')
        const questions = await Questions.find({ _id: ctx.params.questionId })
        const answers = await Answers.find({ questionId: ctx.params.questionId }).populate('answerer')
        ctx.body = {
            questions,
            answers,
            c: ctx.params
        }
    }
    async create(ctx) {
        // // 用户-答案 一对多关系
        // answerer:{
        //     type:mongoose.Schema.Types.ObjectId,
        //         ref:'Users',
        //         required:true,
        //         select:false
        // },
        // // 问题-答案 一对多关系
        // // 问题的id
        // // 答案从属于问题
        // questionId:{
        //     type:String,
        //         required:true
        // },
        ctx.verifyParams({
            content: { type: 'string', required: true },
        })
        // 用户id
        const answerer = ctx.state.user._id
        // 获取问题的id
        const questionId = ctx.params.questionId
        // var answer=await new Answers({...ctx.request.body,answerer,questionId}).save()
        var answer = await Answers.create({ ...ctx.request.body, answerer, questionId })
        ctx.body = answer
    }

    async checkAnswer(ctx, next) {
        const { answer } = ctx.state
        // 作答者，必须和修改答案的用户是同一人
        if (answer.answerer.toString() !== ctx.state.user._id) {
            ctx.throw(403, '没有权限')
        }
        await next()
    }
    async update(ctx) {
        ctx.verifyParams({
            content: { type: 'string', required: false }
        })
        // 之前存储过身份信息，里面包含这条文档
        await ctx.state.answer.update(ctx.request.body)
        ctx.body = ctx.state.answer
    }
    async remove(ctx) {
        await Answers.findByIdAndRemove(ctx.params.id)
        ctx.status = 204
    }
}
module.exports = new AnswersCtl()
